<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Download, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from "axios";

// 查询参数
const queryParams = ref({
  userAccount: '',
  bloodPressureStatus:'0',
  //平均收缩压(mmHg)
  averageSystolicPressure:'0',
  //平均舒张压(mmHg)
  averageDiastolicPressure:'0'
})

// 血压状态选项
const bloodPressureStatusTypeOptions = ref([
  { value: 1, label: '正常' },
  { value: 2, label: '低血压' },
  { value: 3, label: '高血压' }
])

// 排序参数
const sortParams = reactive({
  prop: '',
  order: ''
})
// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框相关
const detailDialogVisible = ref(false)
const currentUser = reactive({
  id: '',
  username: '',
  nickname: ''
})

// 获取血压状态
const getBloodPressureStatus = (systolic, diastolic) => {
  if (systolic < 90 || diastolic < 60) {
    return { status: '低血压', type: 'warning' }
  } else if (systolic >= 140 || diastolic >= 90) {
    return { status: '高血压', type: 'danger' }
  } else if (systolic >= 120 || diastolic >= 80) {
    return { status: '偏高', type: 'info' }
  } else {
    return { status: '正常', type: 'success' }
  }
}

// 获取血压显示样式
const getPressureClass = (value, type) => {
  if (type === 'systolic') {
    if (value < 90) return 'low-pressure'
    if (value >= 140) return 'high-pressure'
    if (value >= 120) return 'pre-high-pressure'
    return 'normal-pressure'
  } else {
    if (value < 60) return 'low-pressure'
    if (value >= 90) return 'high-pressure'
    if (value >= 80) return 'pre-high-pressure'
    return 'normal-pressure'
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '高血压一期': return 'warning'
    case '高血压二期': return 'danger'
    case '低血压': return 'warning'
    case '偏高': return 'info'
    default: return 'success'
  }
}

// 查询数据
// 获取血压数据
const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    //实现查询逻辑
    axios.get(`/health/getHealth/5/${currentPage.value}/${pageSize.value}`).then((response) => {
      console.log(response.data.data);
      total.value = response.data.total;
      tableData.value = response.data.data;
    })

  } catch (error) {
    ElMessage.error('获取数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  try {
    axios.post(`/health/getHealthData/${currentPage.value}/${pageSize.value}`,queryParams.value).then(response => {
      total.value = response.data.total;
      tableData.value = response.data.data;
    })
    ElMessage.success('查询成功')
  } catch (error) {
    ElMessage.error('查询失败')
  }
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    userAccount: '',
    bloodPressureStatus:'0',
    //平均收缩压(mmHg)
    averageSystolicPressure:'0',
    //平均舒张压(mmHg)
    averageDiastolicPressure:'0'
  })
  handleQuery()
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  sortParams.prop = prop
  sortParams.order = order
  fetchData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}
// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 查看详情
const viewDetails = (row) => {
  //
  detailDialogVisible.value = true
}
// 导出数据
const exportData = () => {
  // axios.get(`/health//download/1/${currentPage.value}/${pageSize.value}`).then((response) => {
  location.href = `http://localhost:8080/health/download/1/${currentPage.value}/${pageSize.value}`;
  ElMessage.success('导出成功');
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="blood-pressure-management">
    <!-- 查询区域 -->
    <div class="query-area">
      <el-card shadow="hover">
        <el-form :model="queryParams" label-width="100px" :inline="true">
          <el-form-item label="用户账号">
            <el-input
                v-model="queryParams.userAccount"
                placeholder="请输入用户账号"
                clearable
            />
          </el-form-item>
          <el-col :span="6">
            <el-form-item label="血压状态">
              <el-select
                  v-model="queryParams.bloodPressureStatus"
                  placeholder="请选择血压状态"
                  clearable
              >
                <el-option
                    v-for="item in bloodPressureStatusTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="用户收缩压">
            <el-input
                v-model="queryParams.averageSystolicPressure"
                placeholder="请输入收缩压"
                clearable
            />
          </el-form-item>
          <el-form-item label="用户舒张压">
            <el-input
                v-model="queryParams.averageDiastolicPressure"
                placeholder="请输入用户舒张压"
                clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
            <el-button @click="resetQuery" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据区域 -->
    <div class="data-area">
      <el-card shadow="hover">
        <div class="header">
          <h3>用户血压数据统计</h3>
          <el-button type="primary" @click="exportData" >导出数据</el-button>
        </div>

        <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
            @sort-change="handleSortChange"
        >
          <el-table-column prop="userAccount" label="用户账号" width="150" sortable>
            <template #default="{row}">
              <div style="display: flex; align-items: center;">
                <span>{{ row.userAccount }}</span>
                <el-tag
                    :type="getBloodPressureStatus(row.averageSystolicPressure, row.averageDiastolicPressure).type"
                    style="margin-left: 8px;"
                >
                  {{ getBloodPressureStatus(row.averageSystolicPressure, row.averageDiastolicPressure).status }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="userNickname" label="用户昵称" width="150" />
          <el-table-column prop="averageSystolicPressure" label="平均高压(mmHg)" width="150" sortable>
            <template #default="{row}">
              <span :class="getPressureClass(row.averageSystolicPressure, 'systolic')">
                {{ row.averageSystolicPressure }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="averageDiastolicPressure" label="平均低压(mmHg)" width="150" sortable>
            <template #default="{row}">
              <span :class="getPressureClass(row.averageDiastolicPressure, 'diastolic')">
                {{ row.averageDiastolicPressure }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{row}">
              <el-button
                  type="primary"
                  size="small"
                  @click="viewDetails(row)"
                  :icon="View"
              >详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[1,3,5,10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="`用户血压详情 - ${currentUser.nickname} (${currentUser.username})`"
        width="80%"
    >
      <user-blood-pressure-detail
          v-if="detailDialogVisible"
          :user-id="currentUser.id"
      />
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.blood-pressure-management {
  padding: 20px;
}

.query-area {
  margin-bottom: 20px;
}

.data-area {
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: flex-end;
}

.normal-pressure {
  color: var(--el-color-success);
  font-weight: bold;
}

.low-pressure {
  color: var(--el-color-warning);
  font-weight: bold;
}
.high-pressure {
  color: var(--el-color-danger);
  font-weight: bold;
}
.pre-high-pressure {
  color: var(--el-color-info);
  font-weight: bold;
}
</style>